package com.zhangmeng.tools.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.BufferUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.socket.aio.AioClient;
import cn.hutool.socket.aio.AioSession;
import cn.hutool.socket.aio.SimpleIoAction;
import com.zhangmeng.tools.utils.AlertUtils;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.Date;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-05-06 10:38
 */
public class AioClientSocketController {

    @FXML
    public TextField ip_address;

    @FXML
    public TextArea content;

    @FXML
    public Button connection;

    @FXML
    public TextField input;

    @FXML
    public Button send;

    @FXML
    public TextField port;

    @FXML
    public Button disconn;

    private AioClient client;

    private AioSession aioSession;

    private void appendMsg(String msg) {
        content.appendText(System.lineSeparator());
        content.appendText(msg);
    }

    @FXML
    public void initialize() {
        ip_address.setText("localhost");
        port.setText("8083");
        connection.setOnAction(event -> {
            content.setText(null);
            if (ip_address.getText().length() == 0 ){
                AlertUtils.alert_warning("ip不能为空");
                return;
            }
            if (port.getText().length() == 0 ){
                AlertUtils.alert_warning("端口不能为空");
                return;
            }

            client = new AioClient(new InetSocketAddress(ip_address.getText(), Integer.parseInt(port.getText())), new SimpleIoAction() {

                @Override
                public void doAction(AioSession session, ByteBuffer data) {
                    appendMsg("========>客户端接收"  + new Date()  + "=======>:" + StrUtil.utf8Str(data));
                    if (data.hasRemaining()) {
                    } else {
                        session.read();
                    }
                }

                @Override
                public void failed(Throwable exc, AioSession session) {
                    exc.printStackTrace();
                    super.failed(exc, session);
                }
            });

            client.read();
        });

        send.setOnAction(event -> {
            send();
        });

        disconn.setOnAction(event -> {
            client.close();
        });
    }

    private void send() {
        if (input.getText().length() == 0) {
            AlertUtils.alert_warning("发送的内容不能为空");
            return;
        }
        String msg = input.getText();
        client.write(ByteBuffer.wrap(msg.getBytes()));
        appendMsg("========>客户端发送"  + new Date()  + "=======>:" + msg );
    }
}
